package org.springcloud.plugin.strategy.service.context;

import lombok.extern.slf4j.Slf4j;
import org.springcloud.plugin.framework.strategy.context.AbstractStrategyContextHolder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * author: yanggld
 * date: 2019/12/22 16:00
 * version: 1.0
 * description: ServiceStrategyContextHolder
 */
@Slf4j
public class ServiceStrategyContextHolder extends AbstractStrategyContextHolder {

    @Override
    public String getHeader(String name) {
        ServletRequestAttributes attributes = getRestAttributes();
        if (attributes == null) {
            log.warn("The ServletRequestAttributes object is lost for thread switched probably");
            return null;
        }
        return attributes.getRequest().getHeader(name);
    }

    public ServletRequestAttributes getRestAttributes() {
        RequestAttributes requestAttributes = RestStrategyContext.getCurrentContext().getRequestAttributes();
        if (requestAttributes == null) {
            requestAttributes = RequestContextHolder.getRequestAttributes();
        }

        return (ServletRequestAttributes) requestAttributes;
    }

}
